package response

import (
	"github.com/gin-gonic/gin"
	"github.com/gookit/validate"
	"net/http"
	"strconv"
)

// 封装返回响应的结构体
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// 封装统一返回的结果方法
func Result(code int, msg string, data any, c *gin.Context) {
	c.JSON(http.StatusOK, Response{code, msg, data})
}

// 定义全局返回的结果值
var (
	CODE                  = 20000
	ERROR_CODE            = 40001
	MSG                   = "success"
	VALIDATOR_MAP         = map[string]string{"code": "701", "msg": "属性验证有误"}
	BINDING_PARAMETER_MAP = map[string]string{"code": "702", "msg": "参数绑定有误"}
)

// 成功的方法
func Ok(data interface{}, c *gin.Context) {
	Result(CODE, MSG, data, c)
}
func OkMsgData(msg string, data interface{}, c *gin.Context) {
	Result(CODE, msg, data, c)
}
func OkWithCodeMsg(code int, msg string, c *gin.Context) {
	Result(code, msg, nil, c)
}
func OkWithCodeMsgData(code int, msg string, data interface{}, c *gin.Context) {
	Result(code, msg, data, c)
}
func OkMessage(msg string, c *gin.Context) {
	Result(CODE, msg, map[string]interface{}{}, c)
}
func OkSuccess(c *gin.Context) {
	Result(CODE, MSG, nil, c)
}

// 失败的方法
func Fail(code int, msg string, c *gin.Context) {
	Result(code, msg, map[string]any{}, c)
}
func FailWithMessage(msg string, c *gin.Context) {
	Result(ERROR_CODE, msg, map[string]any{}, c)
}
func FailWithCodeMsg(code int, msg string, c *gin.Context) {
	Result(code, msg, map[string]any{}, c)
}
func FailWithError(err error, c *gin.Context) {
	Result(ERROR_CODE, err.Error(), map[string]any{}, c)
}

func FailWithPermission(c *gin.Context) {
	Result(80001, "权限不足", map[string]any{}, c)
}

// 数据校验的方法
func FailWithValidatorData(validate *validate.Validation, c *gin.Context) {
	all := validate.Errors.All() // 所有的错误信息
	one := validate.Errors.One() // 随机的一条错误信息
	code, _ := strconv.ParseInt(VALIDATOR_MAP["code"], 10, 32)
	Result(int(code), one, all, c)
}

// 绑定参数的方法（如果参数注入失败或者出错就返回）
func FailWithBindParams(c *gin.Context) {
	code, _ := strconv.ParseInt(BINDING_PARAMETER_MAP["code"], 10, 32)
	Result(int(code), BINDING_PARAMETER_MAP["msg"], nil, c)
}
